package com.caiyi.financial.nirvana.sms.gateway.sgip;

import com.caiyi.financial.nirvana.sms.gateway.sgip.message.SGIPMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SGIP协议 数据流编码
 */
public class SGIPStreamEncoder extends MessageToByteEncoder<SGIPMessage> {

    private static final Logger logger = LoggerFactory.getLogger(SGIPStreamEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext context, SGIPMessage message, ByteBuf buff) throws Exception {
        try {
            int size = message.encode(buff);
            message.setTotalLength(size);
            buff.setInt(0, size);

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            logger.error("编码消息:" + message.toString());
            buff.clear();
        }

    }
}
